package base.thread_demo.demo09;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Random;

/**
 * 采用jdk里面 ThreadLocal 实现线程范围内数据共享。假设这里就一个数据需要共享。
 * ThreadLocal类似一个Map来保存共享数据，因为A、B两个业务类是在同一个线程内部执行的，ThreadLocal将共享与线程绑定在一起。
 */
public class ThreadScopeShareData2 {
    private static final Logger log = LoggerFactory.getLogger(ThreadScopeShareData2.class);

    private static ThreadLocal<Integer> local = new ThreadLocal<>();

    public static void main(String[] args) {

        new Thread(()->{
            int data = new Random().nextInt();
            local.set(data);
            log.info("{} has put data :{}", Thread.currentThread().getName(), data);

            new ThreadScopeShareData2().new A().get();
            new ThreadScopeShareData2().new B().get();
        }, "t1").start();

        new Thread(()->{
            int data = new Random().nextInt();
            local.set(data);
            log.info("{} has put data :{}", Thread.currentThread().getName(), data);

            new ThreadScopeShareData2().new A().get();
            new ThreadScopeShareData2().new B().get();
        }, "t2").start();
        
        new Thread(()->{
//            int data = new Random().nextInt();
//            local.set(data);
//            log.info("{} has put data :{}", Thread.currentThread().getName(), data);

            new ThreadScopeShareData2().new A().get();
            new ThreadScopeShareData2().new B().get();
        }, "t3").start();
    }

    class A {
        private final Logger log = LoggerFactory.getLogger(A.class);
        public void get(){
            Integer data = local.get();
            log.info("{}线程------A: {}", Thread.currentThread().getName(), data);
        }
    }

    class B {
        private final Logger log = LoggerFactory.getLogger(B.class);
        public void get(){
            Integer data = local.get();
            log.info("{}线程------B: {}", Thread.currentThread().getName(), data);
        }
    }
}
